﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RoadFlow.Utility;

namespace RoadFlow.IntegrateCore.Areas.RoadFlowCore.Controllers
{
    [Area("RoadFlowCore")]
    public class ProgramDesignerController : Controller
    {
        [Validate]
        public IActionResult Index()
        {
            ViewData["query"] = "appid=" + Request.Querys("appid") + "&tabid=" + Request.Querys("tabid");
            return View();
        }

        [Validate]
        public IActionResult Tree()
        {
            ViewData["appId"] = Request.Querys("appid");
            ViewData["tabId"] = Request.Querys("tabid");
            ViewData["rootId"] = new Business.Dictionary().GetIdByCode("system_applibrarytype");
            return View();
        }

        [Validate]
        public IActionResult List()
        {
            string appId = Request.Querys("appid");
            string tabId = Request.Querys("tabid");
            string typeId = Request.Querys("typeid");

            ViewData["appId"] = appId;
            ViewData["tabId"] = tabId;
            ViewData["typeId"] = typeId;
            ViewData["query"] = "appid=" + appId + "&tabid=" + tabId + "&typeid=" + typeId;
            return View();
        }

        [Validate]
        public string Query()
        {
            string sidx = Request.Forms("sidx");
            string sord = Request.Forms("sord");
            int size = Tools.GetPageSize();
            int number = Tools.GetPageNumber();
            string order = (sidx.IsNullOrEmpty() ? "CreateTime" : sidx) + " " + (sord.IsNullOrEmpty() ? "ASC" : sord);

            string name = Request.Forms("Name");
            string typeid = Request.Querys("typeid");
            string types = string.Empty;
            if (typeid.IsGuid(out Guid tid))
            {
                var dicts = new Business.Dictionary().GetAllChildsId(tid);
                types = dicts.JoinSqlIn();
            }

            System.Data.DataTable dt = new Business.Program().GetPagerData(out int count, size, number, name, types, order);
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            Business.Dictionary dictionary = new Business.Dictionary();
            Business.User user = new Business.User();
            foreach (System.Data.DataRow dr in dt.Rows)
            {
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", dr["Id"].ToString() },
                    { "Name", dr["Name"].ToString() },
                    { "Type", dictionary.GetTitle(dr["Type"].ToString().ToGuid()) },
                    { "CreateTime", dr["CreateTime"].ToString().ToDateTime().ToDateTimeString() },
                    { "CreateUserId", user.GetName(dr["CreateUserId"].ToString().ToGuid()) },
                    { "Status", dr["Status"].ToString().ToInt()==0?"设计中":"已发布" },
                    { "Opation", "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"edit('" + dr["Id"].ToString()
                     +"');return false;\"><i class=\"fa fa-edit (alias)\"></i>编辑</a>" }
                };
                jArray.Add(jObject);
            }
            return "{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}";

        }

        [Validate]
        public IActionResult Edit()
        {
            ViewData["queryString"] = Request.UrlQuery();
            return View();
        }

        [Validate]
        public IActionResult Set_Attr()
        {
            string programId = Request.Querys("programid");
            string typeId = Request.Querys("typeid");
            Model.Program programModel = null;
            if (programId.IsGuid(out Guid pid))
            {
                programModel = new Business.Program().Get(pid);
            }
            if (null == programModel)
            {
                programModel = new Model.Program
                {
                    Id = Guid.NewGuid(),
                    CreateTime = DateExtensions.Now,
                    CreateUserId = Current.UserId
                };
                if (typeId.IsGuid(out Guid tid))
                {
                    programModel.Type = tid;
                }
            }
            string formType = string.Empty;
            if (programModel.FormId.IsGuid(out Guid fid))
            {
                var app = new Business.AppLibrary().Get(fid);
                if (null != app)
                {
                    formType = app.Type.ToString();
                }
            }
            ViewData["queryString"] = Request.UrlQuery();
            ViewData["appTypeOptions"] = new Business.Dictionary().GetOptionsByCode("system_applibrarytype", value: programModel.Type.ToString());
            ViewData["formTypeOptions"] = new Business.Dictionary().GetOptionsByCode("system_applibrarytype", value: formType);
            ViewData["dbconnOptions"] = new Business.DbConnection().GetOptions(programModel.ConnId.ToString());
            return View(programModel);
        }

        [Validate]
        [ValidateAntiForgeryToken]
        public string SaveAttr(Model.Program programModel)
        {
            if (!ModelState.IsValid)
            {
                return Tools.GetValidateErrorMessag(ModelState);
            }
            Business.Program program = new Business.Program();
            if (Request.Querys("programid").IsGuid(out Guid guid))
            {
                var oldModel = program.Get(guid);
                string oldJSON = null == oldModel ? "" : oldModel.ToString();
                program.Update(programModel);
                Business.Log.Add("修改了应用程序设计属性-" + programModel.Name, type: Business.Log.Type.系统管理, oldContents: oldJSON, newContents: programModel.ToString());
            }
            else
            {
                program.Add(programModel);
                Business.Log.Add("添加了应用程序设计属性-" + programModel.Name, programModel.ToString(), Business.Log.Type.系统管理);
            }
            return "保存成功!";
        }

        [Validate]
        public IActionResult Set_ListField()
        {
            Business.ProgramField programField = new Business.ProgramField();
            Business.Dictionary dictionary = new Business.Dictionary();
            var fields = programField.GetAll(Request.Querys("programid").ToGuid());
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            foreach (var field in fields)
            {
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", field.Id },
                    { "fieldName", field.Field },
                    { "showName", field.ShowTitle.IsNullOrEmpty() ? field.Field :field.ShowTitle },
                    { "showType", dictionary.GetTitle("programdesigner_showtype", field.ShowType.ToString()) },
                    { "align", field.Align.Equals("left")?"左对齐":field.Align.Equals("center")?"居中对齐":"右对齐" },
                    { "width", field.Width },
                    { "isSort", field.IsSort==1?"是":"否" },
                    { "isDefaultSort", field.IsDefaultSort==1?"是":"否" },
                    { "sort", field.Sort },
                    { "opation", "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"edit('" + field.Id.ToString()
                     +"');return false;\"><i class=\"fa fa-edit (alias)\"></i>编辑</a>" }
                };
                jArray.Add(jObject);
            }

            ViewData["query"] = "programid=" + Request.Querys("programid") + "&pagesize=" + Request.Querys("pagesize") + "&pagenumber=" + Request.Querys("pagenumber") +
                "&appid=" + Request.Querys("appid") + "&tabid=" + Request.Querys("tabid") + "&typeid=" + Request.Querys("typeid");
            ViewData["list"] = jArray.ToString();
            return View();
        }

        [Validate]
        public IActionResult Set_ListField_Edit()
        {
            string fieldid = Request.Querys("fieldid");
            string programid = Request.Querys("programid");
            var programModel = new Business.Program().Get(programid.ToGuid());
            if (null == programModel)
            {
                return new ContentResult() { Content = "未找到程序设计实体!" };
            }
            Business.ProgramField programField = new Business.ProgramField();
            Model.ProgramField programFieldModel = null;
            if (fieldid.IsGuid(out Guid fid))
            {
                programFieldModel = programField.Get(fid);
            }
            if (null == programFieldModel)
            {
                programFieldModel = new Model.ProgramField
                {
                    Id = Guid.NewGuid(),
                    ProgramId = programModel.Id,
                    Sort = programField.GetMaxSort(programModel.Id),
                    IsSort = 1
                };
            }
            var bindFields = programField.GetAll(programModel.Id);
            List<string> bindFieldList = new List<string>();
            foreach (var f in bindFields)
            {
                if (!f.Field.IsNullOrWhiteSpace())
                {
                    bindFieldList.Add(f.Field);
                }
            }

            Business.Dictionary dictionary = new Business.Dictionary();
            ViewData["queryString"] = Request.UrlQuery();
            ViewData["fieldOptions"] = programField.GetFieldOptions(programModel.ConnId, programModel.SqlString, programFieldModel.Field, bindFieldList);
            ViewData["showTypeOptions"] = dictionary.GetOptionsByCode("programdesigner_showtype", Business.Dictionary.ValueField.Value, programFieldModel.ShowType.ToString());
            ViewData["alignOptions"] = dictionary.GetOptionsByCode("programdesigner_algin", Business.Dictionary.ValueField.Value, programFieldModel.Align);
            return View(programFieldModel);
        }

        [Validate]
        [ValidateAntiForgeryToken]
        public string SaveSet_ListField(Model.ProgramField programFieldModel)
        {
            if (!ModelState.IsValid)
            {
                return Tools.GetValidateErrorMessag(ModelState);
            }
            Business.ProgramField programField = new Business.ProgramField();
            if (Request.Querys("fieldid").IsGuid(out Guid guid))
            {
                var oldModel = programField.Get(guid);
                string oldJSON = null == oldModel ? "" : oldModel.ToString();
                programField.Update(programFieldModel);
                Business.Log.Add("修改了应用程序设计字段-" + programFieldModel.Field, type: Business.Log.Type.系统管理, oldContents: oldJSON, newContents: programFieldModel.ToString());
            }
            else
            {
                programField.Add(programFieldModel);
                Business.Log.Add("添加了应用程序设计字段-" + programFieldModel.Field, programFieldModel.ToString(), Business.Log.Type.系统管理);
            }
            return "保存成功!";
        }

        [Validate]
        public string DeleteSet_ListField()
        {
            string ids = Request.Forms("ids") ?? "";
            List<Model.ProgramField> programFields = new List<Model.ProgramField>();
            Business.ProgramField programField = new Business.ProgramField();
            foreach (string id in ids.Split(','))
            {
                var p = programField.Get(id.ToGuid());
                if (null != p)
                {
                    programFields.Add(p);
                }
            }
            programField.Delete(programFields.ToArray());
            Business.Log.Add("删除了应用程序设计字段", Newtonsoft.Json.JsonConvert.SerializeObject(programFields), Business.Log.Type.系统管理);
            return "删除成功!";
        }

        [Validate]
        public IActionResult Set_Query()
        {
            Business.ProgramQuery programQuery = new Business.ProgramQuery();
            Business.Dictionary dictionary = new Business.Dictionary();
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            foreach (var query in programQuery.GetAll(Request.Querys("programid").ToGuid()))
            {
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", query.Id },
                    { "fieldName", query.Field },
                    { "showTitle", query.ShowTitle.IsNullOrEmpty() ? query.Field : query.ShowStyle },
                    { "operator", query.Operators },
                    { "controlName", query.ControlName },
                    { "inputType", dictionary.GetTitle("programdesigner_inputtype", query.InputType.ToString()) },
                    { "sort", query.Sort },
                    { "opation", "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"edit('" + query.Id.ToString()
                     +"');return false;\"><i class=\"fa fa-edit (alias)\"></i>编辑</a>" }
                };
                jArray.Add(jObject);
            }

            ViewData["query"] = "programid=" + Request.Querys("programid") + "&pagesize=" + Request.Querys("pagesize") + "&pagenumber=" + Request.Querys("pagenumber") +
                "&appid=" + Request.Querys("appid") + "&tabid=" + Request.Querys("tabid") + "&typeid=" + Request.Querys("typeid");
            ViewData["list"] = jArray.ToString();
            return View();
        }

        [Validate]
        public IActionResult Set_Query_Edit()
        {
            string queryid = Request.Querys("queryid");
            string programid = Request.Querys("programid");
            var programModel = new Business.Program().Get(programid.ToGuid());
            if (null == programModel)
            {
                return new ContentResult() { Content = "未找到程序设计实体!" };
            }
            Business.ProgramQuery programQuery = new Business.ProgramQuery();
            Model.ProgramQuery programQueryModel = null;
            if (queryid.IsGuid(out Guid qid))
            {
                programQueryModel = programQuery.Get(qid);
            }
            if (null == programQueryModel)
            {
                programQueryModel = new Model.ProgramQuery
                {
                    Id = Guid.NewGuid(),
                    ProgramId = programModel.Id,
                    Sort = programQuery.GetMaxSort(programModel.Id)
                };
            }
            Business.Dictionary dictionary = new Business.Dictionary();
            ViewData["queryString"] = Request.UrlQuery();
            ViewData["fieldOptions"] = new Business.ProgramField().GetFieldOptions(programModel.ConnId, programModel.SqlString, programQueryModel.Field);
            ViewData["controlTypeOptions"] = dictionary.GetOptionsByCode("programdesigner_inputtype", Business.Dictionary.ValueField.Value, programQueryModel.InputType.ToString());
            ViewData["operatorOptions"] = dictionary.GetOptionsByCode("programdesigner_operators", Business.Dictionary.ValueField.Value, programQueryModel.Operators);
            ViewData["dataSourceOptions"] = dictionary.GetOptionsByCode("programdesigner_datasource", Business.Dictionary.ValueField.Value, programQueryModel.DataSource.ToString());
            ViewData["dbconnOptions"] = new Business.DbConnection().GetOptions(programQueryModel.ConnId);
            return View(programQueryModel);
        }

        [Validate]
        [ValidateAntiForgeryToken]
        public string SaveSet_Query(Model.ProgramQuery programQueryModel)
        {
            if (!ModelState.IsValid)
            {
                return Tools.GetValidateErrorMessag(ModelState);
            }
            if (programQueryModel.DataSource == 1)
            {
                programQueryModel.DictValue = Request.Forms("DataSourceString_dict");
            }
            if (programQueryModel.InputType == 6)
            {
                string DataSource_Organize_Range = Request.Forms("DataSource_Organize_Range");
                string DataSource_Organize_Type_Unit = Request.Forms("DataSource_Organize_Type_Unit");
                string DataSource_Organize_Type_Dept = Request.Forms("DataSource_Organize_Type_Dept");
                string DataSource_Organize_Type_Station = Request.Forms("DataSource_Organize_Type_Station");
                string DataSource_Organize_Type_Role = Request.Forms("DataSource_Organize_Type_Role");
                string DataSource_Organize_Type_User = Request.Forms("DataSource_Organize_Type_User");
                string DataSource_Organize_Type_More = Request.Forms("DataSource_Organize_Type_More");
                string json = "{\"unit\":\""+ DataSource_Organize_Type_Unit + "\",\"dept\":\"" + DataSource_Organize_Type_Dept + "\"," +
                    "\"role\":\"" + DataSource_Organize_Type_Role + "\",\"user\":\"" + DataSource_Organize_Type_User + "\"," +
                    "\"more\":\"" + DataSource_Organize_Type_More + "\",\"station\":\"" + DataSource_Organize_Type_Station + "\"}";
                programQueryModel.OrgAttribute = json;
            }

            Business.ProgramQuery programQuery = new Business.ProgramQuery();
            if (Request.Querys("queryid").IsGuid(out Guid guid))
            {
                var oldModel = programQuery.Get(guid);
                string oldJSON = null == oldModel ? "" : oldModel.ToString();
                programQuery.Update(programQueryModel);
                Business.Log.Add("修改了应用程序设计查询-" + programQueryModel.Field, type: Business.Log.Type.系统管理, oldContents: oldJSON, newContents: programQueryModel.ToString());
            }
            else
            {
                programQuery.Add(programQueryModel);
                Business.Log.Add("添加了应用程序设计查询-" + programQueryModel.Field, programQueryModel.ToString(), Business.Log.Type.系统管理);
            }
            return "保存成功!";
        }

        [Validate]
        public string Delete_Set_Query()
        {
            Business.ProgramQuery programQuery = new Business.ProgramQuery();
            string ids = Request.Forms("ids") ?? "";
            List<Model.ProgramQuery> programQueries = new List<Model.ProgramQuery>();
            foreach (string id in ids.Split(','))
            {
                if (id.IsGuid(out Guid guid))
                {
                    var p = programQuery.Get(guid);
                    if (null != p)
                    {
                        programQueries.Add(p);
                    }
                }
            }
            programQuery.Delete(programQueries.ToArray());
            Business.Log.Add("删除了应用程序设计查询", Newtonsoft.Json.JsonConvert.SerializeObject(programQueries), Business.Log.Type.系统管理);
            return "删除成功!";
        }

        [Validate]
        public IActionResult Set_Button()
        {
            Business.ProgramButton programButton = new Business.ProgramButton();
            Business.Dictionary dictionary = new Business.Dictionary();
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            foreach (var button in programButton.GetAll(Request.Querys("programid").ToGuid()))
            {
                string ico = string.Empty;
                if (!button.Ico.IsNullOrWhiteSpace())
                {
                    if (button.Ico.IsFontIco())
                    {
                        ico = "<i class=\"fa " + button.Ico + "\"></i>";
                    }
                    else
                    {
                        ico = "<img src=\"" + button.Ico + "\"/>";
                    }
                }
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", button.Id },
                    { "buttonName", button.ButtonName },
                    { "ico", ico },
                    { "showType", button.ShowType == 0 ? "工具栏按钮" : button.ShowType == 1 ? "普通按钮" : "列表按钮" },
                    { "isValidate", button.IsValidateShow==1 ? "是" : "否" },
                    { "sort", button.Sort },
                    { "opation", "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"edit('" + button.Id.ToString()
                     +"');return false;\"><i class=\"fa fa-edit (alias)\"></i>编辑</a>" }
                };
                jArray.Add(jObject);
            }

            ViewData["query"] = "programid=" + Request.Querys("programid") + "&pagesize=" + Request.Querys("pagesize") + "&pagenumber=" + Request.Querys("pagenumber") +
                "&appid=" + Request.Querys("appid") + "&tabid=" + Request.Querys("tabid") + "&typeid=" + Request.Querys("typeid");
            ViewData["list"] = jArray.ToString();
            return View();
        }

        [Validate]
        public IActionResult Set_Button_Edit()
        {
            string buttonid = Request.Querys("buttonid");
            string programid = Request.Querys("programid");
            var programModel = new Business.Program().Get(programid.ToGuid());
            if (null == programModel)
            {
                return new ContentResult() { Content = "未找到程序设计实体!" };
            }
            Business.ProgramButton programButton = new Business.ProgramButton();
            Model.ProgramButton programButtonModel = null;
            if (buttonid.IsGuid(out Guid bid))
            {
                programButtonModel = programButton.Get(bid);
            }
            if (null == programButtonModel)
            {
                programButtonModel = new Model.ProgramButton
                {
                    Id = Guid.NewGuid(),
                    ProgramId = programModel.Id,
                    ShowType = -1,
                    Sort = programButton.GetMaxSort(programModel.Id)
                };
            }
            ViewData["queryString"] = Request.UrlQuery();
            return View(programButtonModel);
        }

        [Validate]
        [ValidateAntiForgeryToken]
        public string SaveSet_Button(Model.ProgramButton programButtonModel)
        {
            if (!ModelState.IsValid)
            {
                return Tools.GetValidateErrorMessag(ModelState);
            }
            Business.ProgramButton programButton = new Business.ProgramButton();
            if (Request.Querys("buttonid").IsGuid(out Guid guid))
            {
                var oldModel = programButton.Get(guid);
                string oldJSON = null == oldModel ? "" : oldModel.ToString();
                programButton.Update(programButtonModel);
                Business.Log.Add("修改了应用程序设计按钮-" + programButtonModel.ButtonName, type: Business.Log.Type.系统管理, oldContents: oldJSON, newContents: programButtonModel.ToString());
            }
            else
            {
                programButton.Add(programButtonModel);
                Business.Log.Add("添加了应用程序设计按钮-" + programButtonModel.ButtonName, programButtonModel.ToString(), Business.Log.Type.系统管理);
            }
            return "保存成功!";
        }

        [Validate]
        public string Delete_Set_Button()
        {
            Business.ProgramButton programButton = new Business.ProgramButton();
            string ids = Request.Forms("ids") ?? "";
            List<Model.ProgramButton> programButtons = new List<Model.ProgramButton>();
            foreach (string id in ids.Split(','))
            {
                if (id.IsGuid(out Guid guid))
                {
                    var p = programButton.Get(guid);
                    if (null != p)
                    {
                        programButtons.Add(p);
                    }
                }
            }
            programButton.Delete(programButtons.ToArray());
            Business.Log.Add("删除了应用程序设计按钮", Newtonsoft.Json.JsonConvert.SerializeObject(programButtons), Business.Log.Type.系统管理);
            return "删除成功!";
        }

        [Validate]
        public IActionResult Set_Validate()
        {
            string programid = Request.Querys("programid");
            var programModel = new Business.Program().Get(programid.ToGuid());
            if (null == programModel)
            {
                return new ContentResult() { Content = "未找到程序设计实体!" };
            }
            if (!programModel.FormId.IsGuid(out Guid fid))
            {
                return new ContentResult() { Content = "程序未设置表单!" };
            }
            var applibraryModel = new Business.AppLibrary().Get(fid);
            if (null == applibraryModel)
            {
                return new ContentResult() { Content = "未在应用程序库中找到该表单!" };
            }
            if (!applibraryModel.Code.IsGuid(out Guid cid))
            {
                return new ContentResult() { Content = "不是表单设计器设计的表单，不能设置验证!" };
            }
            var formModel = new Business.Form().Get(cid);
            if (null == formModel)
            {
                return new ContentResult() { Content = "未找到该表单!" };
            }
            Newtonsoft.Json.Linq.JObject formAttr = null;
            try
            {
                formAttr = Newtonsoft.Json.Linq.JObject.Parse(formModel.attribute);
            }
            catch
            {
                return new ContentResult() { Content = "表单属性不是有效的JSON!" };
            }
            string dbConn = formAttr.Value<string>("dbConn");
            string dbTable = formAttr.Value<string>("dbTable");
            Business.DbConnection dbConnection = new Business.DbConnection();
            Dictionary<string, List<Model.TableField>> dicts = new Dictionary<string, List<Model.TableField>>();
            var fields = dbConnection.GetTableFields(dbConn.ToGuid(), dbTable);
            dicts.Add(dbTable, fields);
            var fields1 = new Business.ProgramValidate().GetAll(programModel.Id);
            //加载子表字段
            if (!formModel.SubtableJSON.IsNullOrWhiteSpace())
            {
                Newtonsoft.Json.Linq.JArray subArray = null;
                try
                {
                    subArray = Newtonsoft.Json.Linq.JArray.Parse(formModel.SubtableJSON);
                }
                catch
                { }
                if (null != subArray)
                {
                    foreach (Newtonsoft.Json.Linq.JObject subObject in subArray)
                    {
                        string subTable = subObject.Value<string>("secondtable");
                        if (subTable.IsNullOrWhiteSpace())
                        {
                            continue;
                        }
                        dicts.Add(subTable, dbConnection.GetTableFields(dbConn.ToGuid(), subTable));
                    }
                }
            }
            
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            int i = 0;
            foreach (var dict in dicts)
            {
                foreach (var field in dict.Value)
                {
                    var validateModel = fields1.Find(p => p.TableName.EqualsIgnoreCase(dict.Key) && p.FieldName.EqualsIgnoreCase(field.FieldName));
                    int valueate = null == validateModel ? 0 : validateModel.Validate;
                    Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                    {
                        { "tableName", dict.Key },
                        { "fieldName", field.FieldName },
                        { "fieldNote", field.Comment },
                        {
                            "validateType",
                            "<input type=\"hidden\" name=\"tablename_" + i + "\" value=\"" + dict.Key + "\"/>" +
                        "<input type=\"hidden\" name=\"fieldname_" + i + "\" value=\"" + field.FieldName + "\"/>" +
                        "<input type=\"hidden\" name=\"fieldnote_" + i + "\" value=\"" + field.Comment + "\"/>" +
                        "<input type=\"hidden\" name=\"filedindex\" value=\"" + i + "\"/>" +
                        "<select name=\"valdate_" + i + "\"><option value=\"\"></option>" +
                        "<option value=\"0\""+(0==valueate?" selected=\"selected\"":"")+">不检查</option>" +
                        "<option value=\"1\""+(1==valueate?" selected=\"selected\"":"")+">允许为空,非空时检查</option>" +
                        "<option value=\"2\""+(2==valueate?" selected=\"selected\"":"")+">不允许为空,并检查</option></select>"
                        }
                    };
                    i++;
                    jArray.Add(jObject);
                }
            }
            ViewData["list"] = jArray.ToString();
            ViewData["queryString"] = Request.UrlQuery();
            return View();
        }

        [Validate]
        [ValidateAntiForgeryToken]
        public string SaveSet_Validate()
        {
            string[] filedindexArray = (Request.Forms("filedindex") ?? "").Split(',');
            Business.ProgramValidate programValidate = new Business.ProgramValidate();
            Guid programId = Request.Querys("programid").ToGuid();
            if (programId.IsEmptyGuid())
            {
                return "程序ID错误!";
            }
            List<Model.ProgramValidate> programValidates = new List<Model.ProgramValidate>();
            foreach (string index in filedindexArray)
            {
                string tableName = Request.Forms("tablename_" + index);
                string fieldname = Request.Forms("fieldname_" + index);
                string fieldnote = Request.Forms("fieldnote_" + index);
                string valdate = Request.Forms("valdate_" + index);
                Model.ProgramValidate programValidateModel = new Model.ProgramValidate
                {
                    FieldName = fieldname,
                    FieldNote = fieldnote,
                    Id = Guid.NewGuid(),
                    ProgramId = programId,
                    TableName = tableName,
                    Validate = valdate.ToInt(0)
                };
                programValidates.Add(programValidateModel);
            }
            int i = programValidate.Add(programValidates.ToArray());
            return "保存成功!";
        }

        [Validate]
        public IActionResult Set_Export()
        {
            Business.ProgramExport programExport = new Business.ProgramExport();
            Business.Dictionary dictionary = new Business.Dictionary();
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            foreach (var export in programExport.GetAll(Request.Querys("programid").ToGuid()))
            {
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", export.Id },
                    { "fieldName", export.Field },
                    { "showName", export.ShowTitle.IsNullOrEmpty() ? export.Field : export.ShowTitle },
                    { "showType", dictionary.GetTitle("programdesigner_showtype", export.ShowType.ToString()) },
                    { "dataType", dictionary.GetTitle("programdesigner_exportdatatype", export.DataType.ToString()) },
                    { "align", dictionary.GetTitle("programdesigner_algin", export.Align.ToString()) },
                    { "width", export.Width },
                    { "sort", export.Sort },
                    { "opation", "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"edit('" + export.Id.ToString()
                     +"');return false;\"><i class=\"fa fa-edit (alias)\"></i>编辑</a>" }
                };
                jArray.Add(jObject);
            }

            ViewData["query"] = "programid=" + Request.Querys("programid") + "&pagesize=" + Request.Querys("pagesize") + "&pagenumber=" + Request.Querys("pagenumber") +
                "&appid=" + Request.Querys("appid") + "&tabid=" + Request.Querys("tabid") + "&typeid=" + Request.Querys("typeid");
            ViewData["list"] = jArray.ToString();
            return View();
        }

        [Validate]
        public IActionResult Set_Export_Edit()
        {
            string queryid = Request.Querys("exportid");
            string programid = Request.Querys("programid");
            var programModel = new Business.Program().Get(programid.ToGuid());
            if (null == programModel)
            {
                return new ContentResult() { Content = "未找到程序设计实体!" };
            }
            Business.ProgramExport programExport = new Business.ProgramExport();
            Model.ProgramExport programExportModel = null;
            if (queryid.IsGuid(out Guid qid))
            {
                programExportModel = programExport.Get(qid);
            }
            if (null == programExportModel)
            {
                programExportModel = new Model.ProgramExport
                {
                    Id = Guid.NewGuid(),
                    ProgramId = programModel.Id,
                    Sort = programExport.GetMaxSort(programModel.Id)
                };
            }
            Business.Dictionary dictionary = new Business.Dictionary();
            ViewData["fieldOptions"] = new Business.ProgramField().GetFieldOptions(programModel.ConnId, programModel.SqlString, programExportModel.Field);
            ViewData["dataTypeOptions"] = dictionary.GetOptionsByCode("programdesigner_exportdatatype", Business.Dictionary.ValueField.Value, programExportModel.DataType.ToString());
            ViewData["showTypeOptions"] = dictionary.GetOptionsByCode("programdesigner_showtype", Business.Dictionary.ValueField.Value, programExportModel.ShowType.ToString());
            ViewData["alignOptions"] = dictionary.GetOptionsByCode("programdesigner_algin", Business.Dictionary.ValueField.Value, programExportModel.Align);
            ViewData["queryString"] = Request.UrlQuery();
            return View(programExportModel);
        }

        [Validate]
        [ValidateAntiForgeryToken]
        public string Save_Export(Model.ProgramExport programExportModel)
        {
            if (!ModelState.IsValid)
            {
                return Tools.GetValidateErrorMessag(ModelState);
            }
            Business.ProgramExport programExport = new Business.ProgramExport();
            if (Request.Querys("exportid").IsGuid(out Guid guid))
            {
                var oldModel = programExport.Get(guid);
                string oldJSON = null == oldModel ? "" : oldModel.ToString();
                programExport.Update(programExportModel);
                Business.Log.Add("修改了应用程序设计导出-" + programExportModel.Field, type: Business.Log.Type.系统管理, oldContents: oldJSON, newContents: programExportModel.ToString());
            }
            else
            {
                programExport.Add(programExportModel);
                Business.Log.Add("添加了应用程序设计导出-" + programExportModel.Field, programExportModel.ToString(), Business.Log.Type.系统管理);
            }
            return "保存成功!";
        }

        [Validate]
        public string Delete_Export()
        {
            string[] ids = (Request.Forms("ids") ?? "").Split(',');
            List<Model.ProgramExport> programExports = new List<Model.ProgramExport>();
            Business.ProgramExport programExport = new Business.ProgramExport();
            foreach (string id in ids)
            {
                if (!id.IsGuid(out Guid guid))
                {
                    continue;
                }
                var e = programExport.Get(guid);
                if (null != e)
                {
                    programExports.Add(e);
                }
            }
            programExport.Delete(programExports.ToArray());
            Business.Log.Add("删除了应用程序设计导出", Newtonsoft.Json.JsonConvert.SerializeObject(programExports), Business.Log.Type.系统管理);
            return "删除成功!";
        }

        [Validate]
        public string Copy_Export()
        {
            string programId = Request.Querys("programid");
            List<Model.ProgramField> programFields = new Business.ProgramField().GetAll(programId.ToGuid());
            if (programFields.Count == 0)
            {
                return "没有要复制的字段!";
            }
            List<Model.ProgramExport> programExports = new List<Model.ProgramExport>();
            Business.ProgramExport programExport = new Business.ProgramExport();
            foreach (Model.ProgramField programFieldModel in programFields)
            {
                if (programFieldModel.Field.IsNullOrWhiteSpace())
                {
                    continue;
                }
                Model.ProgramExport programExportModel = new Model.ProgramExport();
                programExportModel.Align = programFieldModel.Align;
                programExportModel.CustomString = programFieldModel.CustomString;
                programExportModel.DataType = 0;
                programExportModel.Field = programFieldModel.Field;
                programExportModel.Id = Guid.NewGuid();
                programExportModel.ProgramId = programFieldModel.ProgramId;
                programExportModel.ShowFormat = programFieldModel.ShowFormat;
                programExportModel.ShowTitle = programFieldModel.ShowTitle;
                programExportModel.ShowType = programFieldModel.ShowType;
                programExportModel.Sort = programFieldModel.Sort;
                //programExportModel.Width = programFieldModel.Width;
                programExports.Add(programExportModel);
                
            }
            programExport.DeleteAndAdd(programExports.ToArray());
            return "复制成功!";
        }

        /// <summary>
        /// 发布
        /// </summary>
        /// <returns></returns>
        [Validate]
        public string Publish()
        {
            string programId = Request.Querys("programid");
            if (!programId.IsGuid(out Guid pid))
            {
                return "ID错误!";
            }
            string msg = new Business.Program().Publish(pid);
            Business.Log.Add("发布了程序设计-" + programId, msg, Business.Log.Type.系统管理);
            return "1".Equals(msg) ? "发布成功!" : msg;
        }

        /// <summary>
        /// 运行
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public IActionResult Run()
        {
            string programId = Request.Querys("programid");
            if (!programId.IsGuid(out Guid pid))
            {
                return new ContentResult() { Content = "ID错误!" };
            }
            Business.Program program = new Business.Program();
            var programRunModel = program.GetRunModel(pid);
            if (null == programRunModel)
            {
                return new ContentResult() { Content = "未找到运行时实体，程序未发布!" };
            }

            //加载按钮
            string appId = Request.Querys("appid");
            List<string> buttonHtml = program.GetButtonHtml(programRunModel, Current.UserId, appId.IsGuid(out Guid aid) ? aid : Guid.Empty);
            programRunModel.Button_Toolbar = buttonHtml[0];
            programRunModel.Button_Normal = buttonHtml[1];
            programRunModel.Button_List = buttonHtml[2];

            //得到编辑表单相关信息
            string edit_url = string.Empty;
            string edit_model = programRunModel.EditModel.ToString();
            string edit_width = programRunModel.Width.GetNumber();
            string edit_height = programRunModel.Height.GetNumber();
            if (programRunModel.FormId.IsGuid(out Guid formId))
            {
                var applibraryModel = new Business.AppLibrary().Get(formId);
                if (null != applibraryModel)
                {
                    edit_url = "/RoadFlowCore/FlowRun/FormEdit?applibraryid=" + applibraryModel.Id.ToString();
                }
            }
            ViewData["edit_url"] = edit_url;
            ViewData["edit_model"] = edit_model;
            ViewData["edit_width"] = edit_width;
            ViewData["edit_height"] = edit_height;
            ViewData["edit_title"] = programRunModel.Name;
            ViewData["pagesize"] = Request.Querys("pagesize");
            ViewData["pagenumber"] = Request.Querys("pagenumber");
            ViewData["backUrl"] = "/RoadFlowCore/ProgramDesigner/Run?programid=" + programId + "&appid=" + Request.Querys("appid")
                + "&rf_appopenmodel=" + Request.Querys("rf_appopenmodel") + "&tabid=" + Request.Querys("tabid");
            ViewData["tabid"] = Request.Querys("tabid");
            ViewData["isToolbar"] = programRunModel.Button_Toolbar.IsNullOrWhiteSpace() ? "0" : "1";//是否有工具栏
            ViewData["isQuery"] = programRunModel.ProgramQueries.Count > 0 ? "1" : "0";//是否有查询
            ViewData["isQueryNewtr"] = programRunModel.ButtonLocation == 0 ? "1" : "0";//是否有新行
            ViewData["query"] = "programid=" + programId + "&appid=" + Request.Querys("appid") + "&tabid=" + Request.Querys("tabid");
            return View(programRunModel);
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public string Run_Query()
        {
            string programId = Request.Querys("programid");
            if (!programId.IsGuid(out Guid pid))
            {
                return "ID错误";
            }
            Business.Program program = new Business.Program();
            var programRunModel = program.GetRunModel(pid);
            if (null == programRunModel)
            {
                return "未找到程序运行时实体";
            }
            int size = Tools.GetPageSize();
            int number = Tools.GetPageNumber();
            System.Data.DataTable dt = program.GetData(programRunModel, Request, size, number, out int count);
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            var user = Current.User;
            foreach (System.Data.DataRow dr in dt.Rows)
            {
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject();
                if (dt.Columns.Contains("id"))//添加ID列
                {
                    jObject.Add("id", dr["id"].ToString());
                }
                foreach (var field in programRunModel.ProgramFields)
                {
                    string value = string.Empty;
                    if (field.Field.IsNullOrWhiteSpace())
                    {
                        if (100 == field.ShowType)
                        {
                            value = Business.Wildcard.Filter(programRunModel.Button_List, user, dr);
                            jObject.Add("opation", value);
                        }
                    }
                    else
                    {
                        value = dt.Columns.Contains(field.Field) ? dr[field.Field].ToString() : "";
                        if (!value.IsNullOrWhiteSpace())
                        {
                            switch (field.ShowType)
                            {
                                case 1://序号

                                    break;
                                case 2://日期时间
                                    if (value.IsDateTime(out DateTime d))
                                    {
                                        value = d.ToString(field.ShowFormat.IsNullOrWhiteSpace() ? "yyyy-MM-dd HH:mm:ss" : field.ShowFormat);
                                    }
                                    break;
                                case 3://数字
                                    if (!field.ShowFormat.IsNullOrWhiteSpace())
                                    {
                                        value = value.ToDecimal().ToString(field.ShowFormat);
                                    }
                                    break;
                                case 4://数据字典ID显示为标题
                                    value = new Business.Dictionary().GetTitles(value);
                                    break;
                                case 5://组织架构显示为名称
                                    value = new Business.Organize().GetNames(value);
                                    break;
                                case 6://自定义
                                    value = Business.Wildcard.Filter(field.CustomString, Current.User, dr);
                                    break;
                                case 7://人员ID显示为姓名
                                    value = new Business.User().GetNames(value);
                                    break;
                            }
                        }
                        jObject.Add(field.Field, value);
                    }
                }
                jArray.Add(jObject);
            }
            return "{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}";
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        [ValidateAntiForgeryToken]
        public string Run_Delete()
        {
            string programId = Request.Querys("programid");
            if (!programId.IsGuid(out Guid pid))
            {
                return "应用程序ID错误";
            }
            Business.Program program = new Business.Program();
            var programRunModel = program.GetRunModel(pid);
            if (null == programRunModel)
            {
                return "未找到程序运行时实体";
            }
            if (!programRunModel.FormId.IsGuid(out Guid fid))
            {
                return "没有设置表单,不能删除!";
            }
            var appModel = new Business.AppLibrary().Get(fid);
            if (null == appModel)
            {
                return "没有找到对应的应用程序库!";
            }
            if (!appModel.Code.IsGuid(out Guid formId))
            {
                return "未找到表单Id!";
            }
            string delids = Request.Forms("delid");
            if (delids.IsNullOrWhiteSpace())
            {
                return "要删除的Id为空!";
            }
            List<string> msgs = new List<string>();
            foreach (string delid in delids.Split(','))
            {
                msgs.Add(new Business.Form().DeleteFormData(formId, delid));
            }
            Business.Log.Add("删除了表单数据 - 应用名称：" + programRunModel.Name + " - 应用ID：" + programRunModel.Id, Newtonsoft.Json.JsonConvert.SerializeObject(msgs), Business.Log.Type.其它, others: "ID：" + delids);
            if (msgs.Count > 0 && "1".Equals(msgs.First()))
            {
                return "{\"success\":1,\"msg\":\"删除成功\"}";
            }
            else
            {
                return "{\"success\":0,\"msg\":\"" + (msgs.Count > 0 ? msgs.First() : "未返回") + "\"}";
            }
        }

        /// <summary>
        /// 导出excel
        /// </summary>
        /// <returns></returns>
        [Validate(CheckApp = false)]
        public void Run_Export()
        {
            string programId = Request.Querys("programid");
            if (!programId.IsGuid(out Guid pid))
            {
                return;
            }
            Business.Program program = new Business.Program();
            var programRunModel = program.GetRunModel(pid);
            if (null == programRunModel)
            {
                return;
            }
            System.Data.DataTable dt = program.GetExportData(programRunModel, Request);
            NPOIHelper.ExportByWeb(dt, programRunModel.ExportHeaderText,
                programRunModel.ExportFileName.IsNullOrWhiteSpace() ? programRunModel.Name + ".xlsx" : programRunModel.ExportFileName,
                Response,
                programRunModel.ExportTemplate);
        }
    }
}